var inetUsage = new XMLHttpRequest();

function tumStart() {

}

function inetLogin() {
  if (!accountName.value || !accountPass.value) {
    //accountPass.value="";
    alert("Please enter a valid username and password.");
  }
  else {
    inetUsageGet(accountName.value,accountPass.value,"checkaccountusage");
  }
}

function inetUsageGet(username,password,page) {
  params="check_username="+username+"&password="+password;
  inetUsage.onreadystatechange = function(){inetUsageStateChanged(inetUsage);};
  inetUsage.open("POST", "https://cyberstore.tpg.com.au/your_account/index.php?function="+page, true);
  inetUsage.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  inetUsage.send(params);
}
function inetUsageStateChanged(obj) {
  gadget.debug.trace("Current Status: "+getReadyState(obj));
  if (obj.readyState==4) {
    gadget.debug.trace("HTTP Status: "+obj.status+" "+obj.statusText);
    var inetData=getRegex(/<td\salign=right><b>Current\sBilling\sPeriod:<\/b>\s(?:Ends:\s.*?<BR>)?Usage\sCharges:\s(.*?)<BR>Peak\sDownloads\sused:\s(.*?)\sMB<br>Off-Peak\sDownloads\sused:\s(.*?)\sMB<\/td>/,obj.responseText);
    if(inetData==null){gadget.debug.error("An error has occured, Regex pattern was not matched.");return;}
    var tpgPlan = getRegex(/<td\salign=right><b>Package\sType:<\/b>\s(.*?)<\/td>/,obj.responseText)[1];
    var tpgAllowance = getPlanData(tpgPlan);
    if (tpgAllowance != null){
      inetPeak=tpgAllowance[0];
      inetOffPeak=tpgAllowance[1];
      inetUploads=tpgAllowance[2];
    }
    else {
      //Default values, Will prompt user later
      inetPeak=25000;
      inetOffPeak=25000;
      inetUploads=false;
    }
    inetEndDate=new Date(getRegex(/<td\svalign=top><b>Expiry\sDate:<\/b>\s(.*?)<\/td>/,obj.responseText)[1]);
    xmlStartDate=obj.responseText.match("<a\\shref=\"index\\.php\\?function=.*?\">Display\\susage\\sfor\\sthe\\speriod\\s(.*?)\\sto\\s"+inetEndDate.getFullYear()+"-"+zeroPad(inetEndDate.getMonth()+1,2)+"-"+zeroPad(inetEndDate.getDate(),2)+"<\\/a><p>")[1];
    inetStartDate=new Date(xmlStartDate.substring(0,4),xmlStartDate.substring(5,7)-1,xmlStartDate.substring(8,10));
    inetDaysLeft=Math.floor((inetEndDate.getTime() - new Date().getTime()) / 86400000)+1;
    inetDaysInMonth=Math.ceil((inetEndDate.getTime()-inetStartDate.getTime())/86400000)
    inetUsageCost=inetData[1];
    inetPeakDL=inetData[2];
    inetOffPeakDL=inetData[3];
    gadget.debug.trace("DaysLeft="+inetDaysLeft);
    gadget.debug.trace("UsageCost="+inetUsageCost);
    gadget.debug.trace("Peak Usage="+inetPeakDL);
    gadget.debug.trace("Off-Peak Usage="+inetOffPeakDL);
    gadget.debug.trace("Peak Allowance="+inetPeak);
    gadget.debug.trace("Off-Peak Allowance="+inetOffPeak);
    gadget.debug.trace("EndDate="+inetEndDate);
    inetPeakBar.width=((inetPeakDL / inetPeak)*100)*1.5;
    inetPeakText.innerText=formatMB(inetPeakDL)+" / "+formatMB(inetPeak);
    inetOffPeakBar.width=((inetOffPeakDL / inetOffPeak)*100)*1.5;
    inetOffPeakText.innerText=formatMB(inetOffPeakDL)+" / "+formatMB(inetOffPeak);
    inetDaysLeftBar.width=(((inetDaysInMonth-inetDaysLeft)/inetDaysInMonth)*100)*1.5;
    inetDaysLeftText.innerText=inetDaysLeft+" Days Remaining";
  }
}

function formatMB(mbTotal) {
  if (isNaN(mbTotal)){
    mbTotal=parseFloat(mbTotal);
  }
  if(mbTotal<1000) {
    return (mbTotal/1).toFixed(3)+"MB";
  }
  else if(mbTotal<1000000) {
    return (mbTotal/1000).toFixed(3)+"GB";
  }
  else {
    return (mbTotal/1000000).toFixed(3)+"TB";
  }
}

function zeroPad(num, width) {
  num = num.toString();
  while (num.length < width)
  num = "0" + num;
  return num;
}

function getRegex(regexp,subject) {
  return regexp.exec(subject);
}

function getReadyState(obj) {
  switch (obj.readyState) {
    case 1:
      return "OPENED";
      break;
    case 2:
      return "HEADERS_RECEIVED";
      break;
    case 3:
      return "LOADING";
      break;
    case 4:
      return "DONE";
      break;
    default:
      return "UNSENT";
      break;
  }
}

function urlencode(str){var hexStr=function(dec){return '%'+dec.toString(16).toUpperCase();};var ret='',unreserved=/[\w.-]/;str=(str+'').toString();for(var i=0,dl=str.length;i<dl;i++){var ch=str.charAt(i);if(unreserved.test(ch)){ret+=ch;}else {var code=str.charCodeAt(i);if(code === 32){ret+='+';}else if(code < 128){ret+=hexStr(code);}else if(code >= 128 && code < 2048){ret+=hexStr((code >> 6) | 0xC0);ret+=hexStr((code & 0x3F) | 0x80);}else if(code >= 2048 && code < 65536){ret+=hexStr((code >> 12) | 0xE0);ret+=hexStr(((code >> 6) & 0x3F) | 0x80);ret+=hexStr((code & 0x3F) | 0x80);}else if(code >= 65536){ret+=hexStr((code >> 18) | 0xF0);ret+=hexStr(((code >> 12) & 0x3F) | 0x80);ret+=hexStr(((code >> 6) & 0x3F) | 0x80);ret+=hexStr((code & 0x3F) | 0x80);}}}return ret;}
function getPlanData(planName){var Peak=0,OffPeak=null,Uploads=false,planData=new XMLHttpRequest;planData.open("GET","http://jeltel.com.au/tools/tpgplans.php?action=get&plan="+urlencode(planName),false);planData.send();if(planData.status==200){planData=planData.responseText.split("\r\n");
for (var i=0,len=planData.length;i<len;++i){
  if (planData[i]){
    switch (planData[i].substr(0,2)) {
      case "R=":
        alert(planData[i].substr(2));
        break;
      case "P=":
        Peak=planData[i].substr(2)
        break;
      case "O=":
        OffPeak=planData[i].substr(2)
        break;
      case "U=":
        Uploads=(planData[i].substr(2)=="TRUE")?true:false;
        break;
      case "C=":
        alert(planData[i].substr(2));
        break;
    }
  }
}
}else{return null;}return new Array(Peak,OffPeak,Uploads);}
